package com.xli.sso.security.provider;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    /**
     * 返回当前URL允许访问的角色列表
     *
     * @param object object
     * @return roles
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        FilterInvocation fi = (FilterInvocation) object;
        String requestUrl = fi.getRequestUrl();

        // 动态加载权限信息，例如从数据库中获取
        List<ConfigAttribute> attributes = new ArrayList<>();
        if ("/admin".equals(requestUrl)) {
            attributes.add(new SecurityConfig("ROLE_ADMIN"));
        }
        else if ("/user".equals(requestUrl)) {
            attributes.add(new SecurityConfig("ROLE_USER"));
        }
        return attributes;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return List.of();
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
